package dev.blogmoon.cn.system.repository;

import cn.hutool.core.io.FileUtil;
import com.google.common.collect.Lists;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;
import dev.blogmoon.cn.common.enums.ErrorCode;
import dev.blogmoon.cn.common.utils.BaseConvert;
import dev.blogmoon.cn.system.enums.FileTypeEnum;
import dev.blogmoon.cn.system.module.FileInfoDTO;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Component
public class FileRepository {

    @Value("${qiniu.access-key}")
    private String accessKey;

    @Value("${qiniu.secret-key}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    private UploadManager uploadManager;

    private Auth auth;

    private BucketManager bucketManager;

    @PostConstruct
    public void init() {
        //4.构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration();
        uploadManager = new UploadManager(cfg);

        //5.获取七牛云提供的 token
        auth = Auth.create(accessKey, secretKey);
        bucketManager = new BucketManager(auth, cfg);
    }


    public List<FileInfoDTO> getFileList(String prefix, String delimiter) {
        try {
            FileListing fileListing = bucketManager.listFilesV2(bucket, prefix, "", 1000, delimiter);
            List<FileInfoDTO> fileInfoDTOS = BaseConvert.convertList(Lists.newArrayList(fileListing.items), item -> {
                FileInfoDTO fileInfoDTO = new FileInfoDTO();
                fileInfoDTO.setFileName(FileUtil.getName(item.key));
                fileInfoDTO.setFilePath(item.key);
                fileInfoDTO.setFileSize(item.fsize);
                fileInfoDTO.setFileType(FileTypeEnum.getByName(item.mimeType).getCode());
                if (Objects.equals(FileTypeEnum.DIR.getCode(), fileInfoDTO.getFileType())) {
                    fileInfoDTO.setIsDir(true);
                }
                fileInfoDTO.setExtendName(FileUtil.getSuffix(item.key));
                return fileInfoDTO;
            });
            if (CollectionUtils.isEmpty(fileInfoDTOS)) {
                fileInfoDTOS = Lists.newArrayList();
            }
            if (fileListing.commonPrefixes.length > 0) {
                for (String commonPrefix : fileListing.commonPrefixes) {
                    FileInfoDTO fileInfoDTO = new FileInfoDTO();
                    fileInfoDTO.setFileName(FileUtil.getName(commonPrefix));
                    fileInfoDTO.setFilePath(commonPrefix);
                    fileInfoDTO.setIsDir(true);
                    fileInfoDTOS.add(fileInfoDTO);
                }
            }
            return fileInfoDTOS;
        } catch (QiniuException e) {
            throw ErrorCode.SYSTEM_ERROR.throwBizException();
        }

    }

    public String upload(MultipartFile file, String url) throws IOException {
        return uploadImageQiniu(file, url);
    }

    public List<String> upload(MultipartFile[] files, String url) throws IOException {
        List<String> pathList = Lists.newArrayList();
        for (MultipartFile file : files) {
            String path = uploadImageQiniu(file, url);
            pathList.add(path);
        }
        return pathList;
    }


    private String uploadImageQiniu(MultipartFile multipartFile, String url) {
        try {
            //1、获取文件上传的流
            byte[] fileBytes = multipartFile.getBytes();
            //2、创建日期目录分隔
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = dateFormat.format(new Date());

            //3、获取文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = url + "/" + datePath + "/" + UUID.randomUUID().toString().replace("-", "") + suffix;

            String upToken = auth.uploadToken(bucket);
            uploadManager.put(fileBytes, filename, upToken);
            return filename;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
